package com.boho.ecp.member.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang.StringUtils;

import cn.boho.framework.context.ActionContext;
import cn.boho.framework.exception.UserOperationException;
import cn.boho.framework.po.ComboPager;
import cn.boho.framework.po.DynaBeanMap;
import cn.boho.framework.po.POUtils;
import cn.boho.framework.po.Pager;
import cn.boho.framework.service.MessageService;
import cn.boho.framework.utils.DateUtils;
import cn.boho.framework.utils.HTMLFilter;

import com.boho.ecp.base.model.Product;
import com.boho.ecp.base.model.UserCookie;
import com.boho.ecp.base.service.CookieService;
import com.boho.ecp.cart.dao.CartDao;
import com.boho.ecp.constant.Base;
import com.boho.ecp.constant.Member;
import com.boho.ecp.member.dao.MemberDao;
import com.boho.ecp.member.dao.TProductCommentDao;
import com.boho.ecp.member.dao.TProductFavoritesDao;
import com.boho.ecp.order.dao.TOrderDao;
import com.boho.ecp.po.TDeliveryAddressPO;
import com.boho.ecp.po.TMemberPO;
import com.boho.ecp.po.TProductFavoritesPO;
import com.boho.ecp.product.service.ProductService;
import com.boho.ecp.util.ArrayUtils;
import com.boho.ecp.util.JsonUtils;
import com.boho.ecp.util.MD5Digester;
import com.google.gson.reflect.TypeToken;

public class MemberService {

	private final static String PARAM_COOKIE = "PARAM_COOKIE";
	
	/**
	 * 注册会员
	 * @param con
	 * @param memberAccount
	 * @param password
	 * @throws Exception
	 */
	public static void register(Connection con, String memberAccount, String password) throws Exception {
		TMemberPO memberPO = new TMemberPO();
		memberPO.setMemberAccount(memberAccount);
		memberPO.setPassword(password);
		memberPO.setCreateDate(new Date());
		POUtils.insert(con, memberPO, false);
	}
	
	/**
	 * 会员登录
	 * @param atx
	 * @param name
	 * @param password
	 * @throws Exception
	 */
	public static void login(ActionContext atx, Connection con, String name, String password) throws Exception{
		login(atx, con, name, password, true);
	}
	
	/**
	 * 会员登录
	 * @param atx
	 * @param name
	 * @param password
	 * @param isMD5
	 * @throws Exception
	 */
	public static void login(ActionContext atx, Connection con, String name, String password, boolean isMD5) throws Exception{
		if(isMD5){
			password = MD5Digester.digest(password);
		}
		DynaBeanMap dbm = MemberDao.getMemberByName(con, name);
		if(dbm != null){
			String pwd = (String)dbm.get("PASSWORD");
			if(pwd.equals(password)){
				String status = (String)dbm.get("MEMBER_STATUS");
				if(status.equals(Member.FREEZE_MEMBER_STATUS)){
					UserOperationException uoe = new UserOperationException();
					atx.setErrorContext("MEMBER_FREEZE_ERROR", MessageService.getMessage("MEMBER_FREEZE_ERROR"), uoe);
					throw uoe;
				}
				
				int memberId = (Integer)dbm.get("MEMBER_ID");
//				atx.setStringValue("MEMBER_PWD", pwd);
				atx.setIntValue("MEMBER_ID", memberId);
				atx.setSessionValue(Member.MEMBER_ID_SESSION, memberId);
				atx.setSessionValue(Member.MEMBER_SESSEION, dbm);
			}
			else{
				UserOperationException uoe = new UserOperationException();
				atx.setErrorContext("MEMBER_PWD_ERROR", MessageService.getMessage("MEMBER_PWD_ERROR"), uoe);
				throw uoe;
			}
		}
		else{
			UserOperationException uoe = new UserOperationException();
			atx.setErrorContext("MEMBER_NOT_EXIST", MessageService.getMessage("MEMBER_NOT_EXIST"), uoe);
			throw uoe;
		}
	}
	
	/**
	 * 检查会员名称是否存在
	 * @param atx
	 * @param name
	 * @throws Exception
	 */
	public static void checkMemberByName(ActionContext atx, Connection con, String name) throws Exception{
		DynaBeanMap dbm = MemberDao.getMemberByName(con, name);
		if(dbm != null){
			UserOperationException uoe = new UserOperationException();
			atx.setErrorContext("MEMBER_NAME_EXIST", MessageService.getMessage("MEMBER_NAME_EXIST"), uoe);
			throw uoe;
		}
	}
	
	/**
	 * 根据登录的会员查询购物车信息
	 * @param atx
	 * @return
	 * @throws Exception
	 */
	public static List<Product> getCartProductListByLoginMember(ActionContext atx, Connection con) throws Exception{
		Integer memberId = (Integer)atx.getSessionValue(Member.MEMBER_ID_SESSION);
		String cookie = CookieService.getValue(atx, PARAM_COOKIE);
		DynaBeanMap dbm = CartDao.getCartByMemberId(con, memberId);
		List<Product> list = new ArrayList<Product>();
		if(dbm == null && StringUtils.isNotEmpty(cookie)){
			UserCookie userCookie = JsonUtils.fromJson(cookie, UserCookie.class);
			list = userCookie.getProduct();
		} else if(dbm != null && StringUtils.isNotEmpty(cookie)){
			List<Product> dbList = JsonUtils.fromJson((String)dbm.get("PRODUCT"), new TypeToken<List<Product>>(){}.getType());
			UserCookie userCookie = JsonUtils.fromJson(cookie, UserCookie.class);
			List<Product> cookieList = userCookie.getProduct();
			if(userCookie.getUid() == 0 && dbList != null && !dbList.isEmpty() && cookieList != null && !cookieList.isEmpty()){
				list = mergeProductList(dbList,cookieList);
			} else if(dbList != null && !dbList.isEmpty()){
				list = dbList;
			} else if(cookieList != null && !cookieList.isEmpty()){
				list = cookieList;
			}
		} else{
			list = ListUtils.EMPTY_LIST;
		}
		atx.setValue("MEMBER_ID", memberId);
		return list;
	}
	
	/**
	 * 合并服务端和客户端购物车的信息
	 * @param list1
	 * @param list2
	 * @return
	 */ 
	private static List<Product> mergeProductList(List<Product> list1, List<Product> list2){
		Map<Integer, Product> m = new HashMap<Integer, Product>();
		for (Product product : list1) {
			m.put(product.getId(), product);
		}
		
		for (Product product : list2) {
			Integer id = product.getId();
			if(m.containsKey(id)){
				Product pro = m.get(id);
				product.setQty(pro.getQty() + product.getQty());
			}
			m.put(id, product);
		}
		List<Product> list = new ArrayList<Product>();
		list.addAll(m.values());
		return list;
	}
	
	/**
	 * 新增收货地址
	 * @param atx
	 * @param con
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	public static Integer addDeliveryAddress(ActionContext atx, Connection con, Integer memberId) throws Exception {
		StringBuffer key = new StringBuffer();
		
		TDeliveryAddressPO tDeliveryAddressPO = new TDeliveryAddressPO();
		tDeliveryAddressPO.setMemberId(memberId);
		tDeliveryAddressPO.setConsigneeName(HTMLFilter.filter(atx.getStringValue("CONSIGNEE_NAME")));
		tDeliveryAddressPO.setProvince(HTMLFilter.filter(atx.getStringValue("PROVINCE")));
		tDeliveryAddressPO.setCity(HTMLFilter.filter(atx.getStringValue("CITY")));
		tDeliveryAddressPO.setCounty(HTMLFilter.filter(atx.getStringValue("COUNTY")));
		tDeliveryAddressPO.setDeliveryAddress(HTMLFilter.filter(atx.getStringValue("DELIVERY_ADDRESS")));
		tDeliveryAddressPO.setZipCode(HTMLFilter.filter(atx.getStringValue("ZIP_CODE")));
		tDeliveryAddressPO.setMobile(HTMLFilter.filter(atx.getStringValue("MOBILE")));
		tDeliveryAddressPO.setTelephone(HTMLFilter.filter(atx.getStringValue("TELEPHONE")));
		tDeliveryAddressPO.setIsDefault(1);
		tDeliveryAddressPO.setCreateBy(memberId.toString());
		tDeliveryAddressPO.setCreateDate(new java.util.Date());
		
		POUtils.insert(con, tDeliveryAddressPO, key);
		return Integer.valueOf(key.toString());
	}
	
	/**
	 * 根据会员ID查询信息
	 * @param con
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	public static DynaBeanMap getMemberInfo(Connection con, Integer memberId) throws Exception {
		return MemberDao.getMemberByPk(con, memberId);
	}
	
	/**
	 * 根据会员ID修改会员信息
	 * @param atx
	 * @param memberId
	 * @throws Exception
	 */
	public static void updateMemberById(ActionContext atx, Connection con, Integer memberId) throws Exception {
		TMemberPO cPO = new TMemberPO();
		TMemberPO vPO = new TMemberPO();
		cPO.setMemberId(memberId);
		vPO.setEmail(HTMLFilter.filter(atx.getStringValue("EMAIL")));
		vPO.setMemberName(HTMLFilter.filter(atx.getStringValue("MEMBER_NAME")));
		vPO.setSex(HTMLFilter.filter(atx.getStringValue("SEX")));
		vPO.setCard(HTMLFilter.filter(atx.getStringValue("CARD")));
		vPO.setBirthday(DateUtils.parse(HTMLFilter.filter(atx.getStringValue("BIRTHDAY")),"yyyy-MM-dd"));
		vPO.setMobile(HTMLFilter.filter(atx.getStringValue("MOBILE")));
		vPO.setTelephone(HTMLFilter.filter(atx.getStringValue("TELEPHONE")));
		vPO.setQq(HTMLFilter.filter(atx.getStringValue("QQ")));
		vPO.setUpdateBy(memberId.toString());
		vPO.setUpdateDate(new java.util.Date());
		POUtils.update(con, cPO, vPO, false);
	}
	
	/**
	 * 修改密码
	 * @param con
	 * @param memberId
	 * @param oldPwd
	 * @param newPwd
	 * @throws Exception
	 */
	public static boolean updateMemberPassword(Connection con, Integer memberId, String oldPwd, String newPwd) throws Exception {
		boolean flag = false;
		DynaBeanMap dbm = getMemberInfo(con, memberId);
		String pwd = (String)dbm.get("PASSWORD");
		String old = MD5Digester.digest(oldPwd);
		if(pwd.equals(old)){
			TMemberPO cPO = new TMemberPO();
			TMemberPO vPO = new TMemberPO();
			cPO.setMemberId(memberId);
			vPO.setPassword(MD5Digester.digest(newPwd));
			vPO.setUpdateBy(memberId.toString());
			vPO.setUpdateDate(new Date());
			POUtils.update(con, cPO, vPO, false);
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 查询会员的订单列表
	 * @param con
	 */
	public static List getOrderListByMemberId(Connection con, Integer memberId){
		
		return null;
	}
	
	/**
	 * 根据会员ID查询收藏夹信息
	 * @param con
	 * @param pager
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	public static ComboPager queryFavList(Connection con, Pager pager, Integer memberId) throws Exception{
		ComboPager comboPager = TProductFavoritesDao.queryTProductFavoritesByPager(con, pager, memberId);
		return comboPager;
	}
	
	/**
	 * 添加收藏产品
	 * @param con
	 * @param productId
	 * @param memberId
	 * @throws Exception
	 */
	public static void addFavortiesProduct(Connection con, Integer productId, Integer memberId) throws Exception{
		DynaBeanMap dbm = TProductFavoritesDao.getTProductFavoritesByPk(con, productId, memberId);
		if(dbm != null){
			return;
		}
		
		Date date = new Date();
		TProductFavoritesPO productFavoritesPO = new TProductFavoritesPO();
		productFavoritesPO.setMemberId(memberId);
		productFavoritesPO.setProductId(productId);
		productFavoritesPO.setFavoritesDate(date);
		productFavoritesPO.setCreateBy(memberId.toString());
		productFavoritesPO.setCreateDate(date);
		POUtils.insert(con, productFavoritesPO, false);
		
		ProductService.updateFavByProductId(con, productId);
	}
	
	/**
	 * 根据ID删除收藏夹信息
	 * @param con
	 * @param favId
	 * @throws Exception
	 */
	public static void deleteFavortiesProduct(Connection con, Integer favId, Integer memberId) throws Exception{
		TProductFavoritesPO cPO = new TProductFavoritesPO();
		TProductFavoritesPO vPO = new TProductFavoritesPO();
		cPO.setProductFavoritesId(favId);
		vPO.setIsValid(Base.INVALID);
		vPO.setUpdateBy(memberId.toString());
		vPO.setUpdateDate(new Date());
		POUtils.update(con, cPO, vPO, false);
	}
	
	/**
	 * 会员根据订单编号查询评论内容
	 * @param con
	 * @param orderId
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	public static DynaBeanMap queryCommentByOrderId(Connection con, String orderId, Integer memberId) throws Exception{
		DynaBeanMap m = new DynaBeanMap();
		List productList = TOrderDao.getOrderDetailById(con, orderId);
		List idList = new ArrayList();
		for (Object object : productList) {
			DynaBeanMap dbm = (DynaBeanMap)object;
			idList.add((Integer)dbm.get("PRODUCT_ID"));
		}
		String ids = ArrayUtils.toString(idList);
		List commentList = TProductCommentDao.queryTProductCommentListByIds(con, memberId, ids);
		m.put("PRODUCT_LIST", productList);
		m.put("COMMENT_LIST", commentList);
		return m;
	}
	
	public static void main(String[] args) {
		Map<Integer, Integer> m = new HashMap<Integer, Integer>();
		m.put(new Integer(1), 1);
		System.out.println(m.containsKey(new Integer(1)));
	}
}
